<template>
    <div class="mall-home">
        <!-- 整体滚动容器 -->
        <div class="scroll-container" ref="scrollContainer" @scroll="handleScroll">
            <!-- 顶部横条 -->
            <header class="top-bar">
                <input type="text" v-model="searchQuery" placeholder="搜索商品" class="search-bar" />
                <div class="login-icon" @click="handleLoginClick">
                    {{ isLoggedIn ? '用户' : '登录' }}
                </div>
            </header>

            <!-- 商品轮播 -->
            <div class="carousel-container" v-if="items.length > 1">
                <el-carousel :interval="carouselInterval" arrow="always" autoplay height="300px"
                    indicator-position="outside">
                    <el-carousel-item v-for="(item, index) in items" :key="item.id">
                        <img :src="item.imageUrl" alt="商品图片" class="carousel-image"
                            @click="handleItemClick(item.productId)" />
                        <p>{{ item.title }}</p>
                    </el-carousel-item>
                </el-carousel>
            </div>

            <!-- 商品浏览部分 -->
            <div class="product-list">
                <div class="product-row">
                    <div class="product-column">
                        <div class="product-card" v-for="(product, index) in displayedProductsLeft" :key="product.id">
                            <img :src="product.imageUrl" alt="商品图片" class="product-image" />
                            <div class="product-info">
                                <h3>{{ product.name }}</h3>
                                <p>{{ product.description }}</p>
                                <p class="price">￥{{ product.price }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧列 - 广告位与商品 -->
                    <div class="product-column">
                        <div class="ad-card">
                            <p>广告</p>
                        </div>
                        <div class="product-card" v-for="(product, index) in displayedProductsRight" :key="product.id">
                            <img :src="product.imageUrl" alt="商品图片" class="product-image" />
                            <div class="product-info">
                                <h3>{{ product.name }}</h3>
                                <p>{{ product.description }}</p>
                                <p class="price">￥{{ product.price }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部导航 -->
        <footer class="bottom-bar">
            <div class="nav-icon" @click="navigateTo('/')">首页</div>
            <div class="nav-icon" @click="jing">秒杀</div>
            <div class="nav-icon" @click="jing">订单</div>
            <div class="nav-icon" @click="navigateTo('/manage')">管理</div>
        </footer>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const searchQuery = ref('');
const router = useRouter();
const isLoggedIn = ref(localStorage.getItem('Authorization') !== null);
const carouselInterval = ref(2500); // 轮播图时间间隔

// 声明 scrollContainer ref
const scrollContainer = ref<HTMLElement | null>(null);

// 商品数据
const items = ref([]);
const allProducts = ref([]);
const displayedProductsLeft = ref([]);
const displayedProductsRight = ref([]);

// 防止重复加载
const loading = ref(false);

// 定时器 ID 用于清除
let timeoutId: ReturnType<typeof setTimeout>;

// 登录状态点击
const handleLoginClick = () => {
    if (isLoggedIn.value) {
        router.push('/user');
    } else {
        router.push('/login');
    }
};

// 处理轮播图点击商品事件
const handleItemClick = (productId: number) => {
    router.push(`/product/${productId}`); // 假设商品详情页路径为 /product/:id
    

};

// 导航到其他页面
const navigateTo = (path: string) => {
    router.push(path);
};
const jing = () => {
    alert("敬请期待~");
};

// 获取推荐商品数据
const fetchRecommendedItems = async () => {
    try {
        const response = await axios.get('http://localhost:8080/carousel/list');
        if (response.data.code === 200) {
            items.value = response.data.data.map(item => ({
                id: item.id,
                productId: item.productId,
                imageUrl: item.imageUrl,
                title: item.title,
            }));
        } else {
            console.error('获取推荐商品失败:', response.data.msg);
        }
    } catch (error) {
        console.error('获取推荐商品异常:', error);
    }
};

// 获取商品数据
const fetchProducts = async () => {
    try {
        const response = await axios.get('http://localhost:8080/product/list');
        if (response.data.code === 200) {
            allProducts.value = response.data.data;
            loadMoreProducts(); // 加载商品
        } else {
            console.error('获取商品数据失败:', response.data.msg);
        }
    } catch (error) {
        console.error('获取商品数据异常:', error);
    }
};

// 加载更多商品
const loadMoreProducts = () => {
    if (loading.value) return; // 如果正在加载，则不触发新请求
    loading.value = true; // 开始加载

    // 获取所有商品数据
    const nextProducts = allProducts.value;

    // 轮流插入商品到左右列
    nextProducts.forEach((product, index) => {
        if (index % 2 === 0) {
            // 偶数位置的商品插入到左侧
            displayedProductsLeft.value.push(product);
        } else {
            // 奇数位置的商品插入到右侧
            displayedProductsRight.value.push(product);
        }
    });

    // 模拟延时加载
    setTimeout(() => {
        loading.value = false; // 模拟网络请求的延迟，加载完成后解除锁定
    }, 1000); // 延时模拟
};


// 滚动加载更多商品
const handleScroll = () => {
    const container = scrollContainer.value;
    if (loading.value) return; // 如果正在加载，则不触发新请求

    if (container && container.scrollHeight - container.scrollTop <= container.clientHeight + 100) {
        // 滚动到页面底部，启动定时器
        if (timeoutId) {
            clearTimeout(timeoutId); // 清除上一个定时器
        }

        timeoutId = setTimeout(() => {
            loading.value = true; // 开始加载
            fetchProducts(); // 获取商品数据
            loadMoreProducts(); // 加载更多商品
        }, 1500); // 停留 3 秒后执行
    }
};

// 初始加载
onMounted(() => {
    fetchRecommendedItems();
    fetchProducts();
});

onUnmounted(() => {
    if (timeoutId) {
        clearTimeout(timeoutId); // 清理定时器
    }
});
</script>

<style scoped>
.mall-home {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

/* 滚动容器 */
.scroll-container {
    overflow-y: auto;
    flex: 1;
    padding-bottom: 50px;
}

/* 顶部横条 */
.top-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #1baeae;
    padding: 10px;
    color: #fff;
}

.search-bar {
    flex: 1;
    padding: 5px 10px;
    margin-right: 10px;
    border: none;
    border-radius: 4px;
    outline: none;
}

.login-icon {
    width: 40px;
    height: 40px;
    background-color: #fff;
    color: #1baeae;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    cursor: pointer;
}

/* 商品轮播 */
.carousel-container {
    width: 100%;
    margin: 20px auto;
    border: 2px solid #ddd;
    border-radius: 10px;
    overflow: hidden;
}

.carousel-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    cursor: pointer;
}

/* 商品列样式 */
.product-list {
    display: flex;
    flex-direction: column;
}

.product-row {
    display: flex;
    margin-top: 20px;
}

.product-column {
    width: 50%;
    padding: 10px;
}

/* 商品卡片 */
.product-card {
    background-color: #fff;
    padding: 10px;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
}

.product-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    border-radius: 8px;
}

.product-info {
    padding: 10px 0;
}

.price {
    color: #f66;
    font-size: 18px;
}

/* 广告位 */
.ad-card {
    background-color: #ff0;
    padding: 10px;
    border-radius: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
}

/* 底部导航 */
.bottom-bar {
    display: flex;
    justify-content: space-around;
    background-color: #f5f5f5;
    padding: 10px 0;
}

.nav-icon {
    flex: 1;
    text-align: center;
    padding: 10px;
    color: #333;
    font-size: 14px;
    cursor: pointer;
}

.nav-icon:hover {
    background-color: #e0e0e0;
}
</style>
